﻿using System;
using System.Windows.Forms;
using Timer = System.Timers.Timer;

namespace CreateHandouts {
    public partial class ProgressForm : Form {
        // int containing the total number of slides
        private int Slides;
        // timespan for displaying the elapsed time
        private TimeSpan _timespan;

        // delegates used for cross-thread callbacks for updating ExportProgressLabel & ElapsedTimeLabel
        private delegate void ExportProgressLabelCallback(string text);
        private delegate void ElapsedTimeLabelCallback(string text);

        public ProgressForm(int slides) {
            Slides = slides;
            InitializeComponent();
        }

        // public method to update the ProgressForm from the main thread
        public void UpdateProgressSlide() {
            progressBar.BeginInvoke(new Action(() => progressBar.Value++));            
            SetExportProgressLabelText(String.Format("Slide {0} of {1}", progressBar.Value, Slides));            
        }

        // thread-safe update ExportProgressLabel.Text
        private void SetExportProgressLabelText(string text) {           
            if (ExportProgressLabel.InvokeRequired) {
                ExportProgressLabelCallback exportProgressLabelCallback = SetExportProgressLabelText;
                Invoke(exportProgressLabelCallback, new object[] { text });
            } else {                
                ExportProgressLabel.Text = text;    
            }
        }

        // thread-safe update ElapsedTimeLabel.Text
        private void SetElapsedTimeLabelText(string text) {
            if (elapsedTimeLabel.InvokeRequired) {
                ElapsedTimeLabelCallback textLabelCallback = SetElapsedTimeLabelText;
                Invoke(textLabelCallback, new object[] { text });
            } else {
                elapsedTimeLabel.Text = text;
            }
        }

        private void ProgressForm_Load(object sender, EventArgs e) {      
            // initialize a timer with a one second interval
            elapsedTimeLabel.Text = string.Empty;
            var timer = new Timer(1000);
            timer.Elapsed += timer_Elapsed;
            timer.Start();

            progressBar.Minimum = 0;
            progressBar.Maximum = Slides;
            progressBar.Value = 1;
            ExportProgressLabel.Text = String.Format("Slide {0} of {1}", 1, Slides);
        }

        void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
            // set the ElapsedTimeLabel.Text every tick (=1s)
            _timespan = _timespan.Add(new TimeSpan(0, 0, 0, 1));
            SetElapsedTimeLabelText(String.Format("Elapsed Time: {0}:{1}", _timespan.Minutes < 10 ? "0" + _timespan.Minutes : _timespan.Minutes.ToString(), _timespan.Seconds < 10 ? "0" + _timespan.Seconds : _timespan.Seconds.ToString()));
        }            
    }
}
